package cn.daniel.framework.idgenerator;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author daniel.tuen
 * @date 2025/9/16 15:23
 * @description
 */
@Component
public class DataCenterIdHolder {

    private static Logger logger = LoggerFactory.getLogger(DataCenterIdHolder.class);

    /**
     * 持有当前服务的Data Center ID（初始化后固定）
     */
    private final int dataCenterId;

    /**
     * 注入Nacos发现配置，读取元数据
     * @param nacosDiscoveryProperties
     */
    @Autowired
    public DataCenterIdHolder(NacosDiscoveryProperties nacosDiscoveryProperties) {
        // 从元数据中获取data-center-id，默认值0（防止配置缺失）
        String dcIdStr = nacosDiscoveryProperties.getMetadata().getOrDefault("data-center-id", "0");
        this.dataCenterId = Integer.parseInt(dcIdStr);
        logger.info("从Nacos 获取到元数据: data-center-id = {}", dataCenterId);
    }

    /**
     * 提供获取Data Center ID的方法，供ID生成逻辑使用
     * @return
     */
    public int getDataCenterId() {
        return dataCenterId;
    }
}
